package com.cloudgateway.config;

import com.alibaba.fastjson.JSON;
import com.cloudgateway.client.AuthApi;
import com.cloudgateway.client.LoginInfo;
import com.common.global.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;

@Component
@Slf4j
public class AuthFilterConfig implements GlobalFilter, Ordered {

    public static final ThreadLocal<ServerHttpRequest> requestThreadLocal = new ThreadLocal<>();

    @Autowired
    private AuthApi authApi;

    @Value("${token.filter.ignore:}")
    private String ignoreUrls;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        AuthFilterConfig.requestThreadLocal.set(request);
        if (shouldFilter(exchange)) {
            log.info("请求地址 :" + request.getURI().getPath());
            HttpHeaders headers = request.getHeaders();
            String token = headers.getFirst("token");
            if (StringUtils.isEmpty(token)) {
                return GatewayR.error(exchange, "非法访问");
            }

            R<LoginInfo> loginInfo = authApi.authenticationInfo(token);
            if (null == loginInfo || !String.valueOf(HttpStatus.OK.value()).equals(loginInfo.getCode())) {
                log.info(JSON.toJSONString(loginInfo));
                return GatewayR.error(exchange, loginInfo.getMessage());
            }
            if (null == loginInfo.getData() || StringUtils.isEmpty(loginInfo.getData().getUserId())) {
                return GatewayR.error(exchange, "用户已过期");
            }
            request = request.mutate()
                    .header("h-userName", loginInfo.getData().getUserName())
                    .header("h-userId", loginInfo.getData().getUserId())
                    .header("h-roles", JSON.toJSONString(loginInfo.getData().getRoles()))
                    .header("h-auths", JSON.toJSONString(loginInfo.getData().getAuths()))
                    .build();
        }
        return chain.filter(exchange.mutate().request(request).build());
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE + 100;
    }

    public boolean shouldFilter(ServerWebExchange exchange) {
        AntPathMatcher matcher = new AntPathMatcher();
        ServerHttpRequest request = exchange.getRequest();
        for (String ignoreUrl : Arrays.asList(ignoreUrls.split(";"))) {
            if (matcher.match(ignoreUrl, request.getURI().getPath())) {
                return false;
            }
        }
        return true;
    }
}
